/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.dp.impl;

import com.plian.Tools.*;
import com.plian.system.dto.dp.UprightDisciplinedDTO;
import com.plian.system.entity.dp.UprightDisciplined;
import com.plian.system.mapper.dp.UprightDisciplinedMapper;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.dp.IUprightDisciplinedService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.dp.UprightDisciplinedVO;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.wrapper.dp.UprightDisciplinedWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 服务实现类
 *
 * @author gangan
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class UprightDisciplinedServiceImpl extends BaseServiceImpl<UprightDisciplinedMapper, UprightDisciplined> implements IUprightDisciplinedService
//		, BaseFlowService
{

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private FileService fileService;

	private UprightDisciplinedWrapper uprightDisciplinedWrapper;

//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public boolean saveOrUpdate(UprightDisciplined uprightDisciplined) {
//		if (!Optional.ofNullable(uprightDisciplined.getStatus()).isPresent()) {
//			uprightDisciplined.setStatus(FormStatusConstant.UNREVIEWED);
//		}
//		boolean flag = false;
//		if (uprightDisciplined.getId()==null){
//			flag = true;
//			uprightDisciplined.setCode(formCodeService.getCode(FormTypeConstant.DP_UPRIGHT_DISCIPLINED_FORM));
//			uprightDisciplined.setFormType(String.valueOf(FormTypeConstant.DP_UPRIGHT_DISCIPLINED_FORM));
//			uprightDisciplined.setVersion("1");
//		}
//		if (Optional.ofNullable(uprightDisciplined.getFillingTime()).isPresent()){
//			uprightDisciplined.setDef1(DateUtil.format(uprightDisciplined.getFillingTime(), DateUtil.PATTERN_MONTH));
//		}
//
//		boolean result = super.saveOrUpdate(uprightDisciplined);
//		if (flag){
//			fileService.saveAll(String.valueOf(uprightDisciplined.getId()), uprightDisciplined.getDocList());
//		}else {
//			fileService.edit(String.valueOf(uprightDisciplined.getId()), uprightDisciplined.getDocList());
//		}
//		return result;
//	}
//
//	@Override
//	@Transactional(rollbackFor=RuntimeException.class)
//	public boolean deleteLogic(List<Long> ids) {
//		for (Long id : ids) {
//			UprightDisciplined uprightDisciplined = getById(id);
//			if (uprightDisciplined == null) {
//				return false;
//			} else if (uprightDisciplined.getStatus() != null &&
//					(uprightDisciplined.getStatus() != FormStatusConstant.STASH && uprightDisciplined.getStatus() != FormStatusConstant.UNREVIEWED)) {
//				return false;
//			}
//			formWorkflowService.deleteProcessInstance(String.valueOf(id));
//		}
//		return super.deleteLogic(ids);
//	}
//	@Override
//	public java.io.File exportExcel(JSONObject jsonObject) {
//		List<SearchEntity> entityList = Optional.ofNullable(jsonObject.getJSONArray("query"))
//			.map(x -> x.toJavaList(SearchEntity.class)).orElse(new ArrayList<>());
//		QueryWrapper<UprightDisciplined> qw= SearchParamEntiy.getQueryWrapper(
//			Condition.getQueryWrapper(new UprightDisciplined()), entityList
//		);
//
//		List<UprightDisciplined> floors = list(qw);
////		return ExcelUtils.exportExcelByList(jsonObject, UprightDisciplinedWrapper.build().listVO(floors));
//		return null;
//	}
//
//	@Override
//	public HashMap<String,Object> commit(String id) {
//		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
//
//		//将需要提交的流程变量返回，用于工作流侧
//		return new HashMap<String,Object>();
//	}
//
//	@Override
//	public Boolean finish(String id) {
//		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
//	}
//
//	@Override
//	public Boolean reject(String id, int formState, String comment) {
//		return handleStatus(Long.valueOf(id), formState);
//	}
//
//
//	/**
//	 * 统一处理状态机事件方法
//	 *
//	 * @param id          主键
//	 * @param updateStatus  更新状态
//	 * @return boolean
//	 */
//	private Boolean handleStatus(Long id, int updateStatus) {
//		try {
//			UprightDisciplined uprightDisciplined = getById(id);
//			/**
//			 * 设置审批人和审批时间
//			 */
//			if (updateStatus == FormStatusConstant.FINISH){
//				uprightDisciplined.setApprovedUser(TokenUtil.getTokenUserId());
//				Date now = DateUtil.now();
//				uprightDisciplined.setApprovedTime(now);
//			}
//			uprightDisciplined.setStatus(updateStatus);
//			updateById(uprightDisciplined);
//			return true;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//			return false;
//		}
//	}
//
//	@Override
//	public Boolean checkIsExisted(Long id, String code) {
//
//		boolean result = true;
//		if (Optional.ofNullable(code).isPresent()) {
//			UprightDisciplined uprightDisciplined = new UprightDisciplined();
//			uprightDisciplined.setCode(code);
//			if (Optional.ofNullable(getOne(Condition.getQueryWrapper(uprightDisciplined))).isPresent()) {
//				if (id == null || !id.equals(getOne(Condition.getQueryWrapper(uprightDisciplined)).getId())) {
//					result = false;
//				}
//			}
//		}
//
//		return result;
//	}

	@Override
	public ReportReturnVO selectUprightDisciplineMain(UprightDisciplinedDTO uprightDisciplinedDTO){
		ReportReturnVO reportReturnVO =new ReportReturnVO();
		ReportVO reportVO=new ReportVO();

		reportVO
			.addHeader(HeaderVO.builder().key("fillingUnitName").title("填报单位").build())
			.addHeader(HeaderVO.builder().key("fillingTime").title("填表年月").build())
			.addHeader(HeaderVO.builder().key("companyName").title("单位名称").build())
			.addHeader(HeaderVO.builder().key("specialAction").title("专项行动（次）").build())
			.addHeader(HeaderVO.builder().key("dispatchPersonnel").title("出动人员（人次）").build())
			.addHeader(HeaderVO.builder().key("inspectionUnit").title("检查单位（家）").build())
			.addHeader(HeaderVO.builder().key("discoverProblems").title("发现问题（起）").build())
			.addHeader(HeaderVO.builder().key("handler").title("处理人员（人）").build())
			.addHeader(HeaderVO.builder().key("announcement").title("下发通报（起）").build())
			.addHeader(HeaderVO.builder().key("mediaExposure").title("媒体曝光（起）").build())
			.addHeader(HeaderVO.builder().key("other").title("其他").build());

		List<UprightDisciplinedVO> list= uprightDisciplinedWrapper.entityToVO(
				baseMapper.selectPropertyRegistrationMain(uprightDisciplinedDTO.getFillingDate(),uprightDisciplinedDTO.getFillingUnitIds()));

		UprightDisciplinedVO end = new UprightDisciplinedVO();
		end.setFillingUnitName("总计：" + (CollectionUtil.isNotEmpty(list) ? list.size():0));
		if (CollectionUtil.isNotEmpty(list)){
			for (UprightDisciplinedVO vo : list){
				end.setSpecialAction(BigDecimalUtil.integerAdd(vo.getSpecialAction(), end.getSpecialAction()));
				end.setDispatchPersonnel(BigDecimalUtil.integerAdd(vo.getDispatchPersonnel(), end.getDispatchPersonnel()));
				end.setInspectionUnit(BigDecimalUtil.integerAdd(vo.getInspectionUnit(), end.getInspectionUnit()));
				end.setDiscoverProblems(BigDecimalUtil.integerAdd(vo.getDiscoverProblems(), end.getDiscoverProblems()));
				end.setHandler(BigDecimalUtil.integerAdd(vo.getHandler(), end.getHandler()));

				end.setAnnouncement(BigDecimalUtil.integerAdd(vo.getAnnouncement(), end.getAnnouncement()));
				end.setMediaExposure(BigDecimalUtil.integerAdd(vo.getMediaExposure(), end.getMediaExposure()));
				end.setOther(BigDecimalUtil.integerAdd(vo.getOther(), end.getOther()));
			}
			list.add(end);
		}

		reportVO.setData(list);
		reportReturnVO.setGrids(reportVO);
		return  reportReturnVO;


	}

//	@Override TODO DEL
//	public List<PageData> findByIds(List<String> formIds) {
//		List<UprightDisciplined> uprightDisciplineds = list(new LambdaQueryWrapper<UprightDisciplined>().in(UprightDisciplined::getId,Func.toLongList(StringUtils.join(formIds, StringPool.COMMA))));
//		List<UprightDisciplinedVO> uprightDisciplinedVOS = uprightDisciplinedWrapper.entityToVO(uprightDisciplineds);
//		List<PageData> pageDataList = new ArrayList<>();
//		try{
//			if (CollectionUtil.isNotEmpty(uprightDisciplinedVOS)){
//				for (UprightDisciplinedVO vo : uprightDisciplinedVOS){
//					PageData pd = new PageData();
//					pd.put("id", vo.getId());
//					pd.put("UNITNAME", vo.getFillingUnitName());
//					pd.put("APPLICANTNAME", vo.getCreateUserName());
//					pd.put("applicantId", vo.getCreateUser());
//					pd.put("applyOrganizationId", vo.getFillingUnitId());
//					pd.put("formType", FormTypeConstant.DP_UPRIGHT_DISCIPLINED_FORM);
//					pd.put("orgName", vo.getFillingUnitName());
//					pageDataList.add(pd);
//				}
//			}
//
//			return pageDataList;
//		} catch (Exception e) {
//			log.error(ExceptionUtils.getFullStackTrace(e));
//		}
//		return pageDataList;
//	}
//
//	@Override
//	public List<Integer> getFormType() {
//		return Arrays.asList(FormTypeConstant.DP_UPRIGHT_DISCIPLINED_FORM);
//	}
//
//	@Override
//	public void goBackToStash(String formId) {
//		handleStatus(Long.valueOf(formId), UNREVIEWED);
//	}
//
//	@Override
//	public String checkFillingTime(UprightDisciplined uprightDisciplined){
//		if (!Optional.ofNullable(uprightDisciplined.getFillingTime()).isPresent()) {
//			return "填报时间为空";
//		}
//		if (!Optional.ofNullable(uprightDisciplined.getFillingUnitId()).isPresent()){
//			return "填报单位为空";
//		}
//		UprightDisciplined one = getOne(new LambdaQueryWrapper<UprightDisciplined>()
//		.eq(UprightDisciplined::getFillingUnitId,uprightDisciplined.getFillingUnitId())
//		.eq(UprightDisciplined::getDef1,DateUtil.format(uprightDisciplined.getFillingTime(), DateUtil.PATTERN_MONTH)));
//		if (!Optional.ofNullable(one).isPresent()){
//			return null;
//		}
//		if (one.getId().equals(uprightDisciplined.getId())){
//			return null;
//		}
//		return "该月份已填报";
//	}
}
